package com.dream.service.recommender.hub.rec;

import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.response.BaseListResponse;
import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.service.designer.api.app.DesignerAppService;
import com.dream.service.procure.domain.enums.StockStatus;
import com.dream.service.product.domain.entity.SpuBase;
import com.dream.service.recommender.hub.util.CacheUtil;
import com.dream.service.recommender.hub.util.ParamUtil;
import com.dream.service.recommender.toolkits.cache.RedisCache;
import com.dream.service.recommender.toolkits.utils.ConfigUtil;
import com.dream.service.recommender.toolkits.utils.StringUtils;
import com.dream.service.search.api.SearchRecallService;
import com.dream.service.search.domain.entity.ProductRecallResult;
import com.dream.service.search.domain.request.ProductSearchRequest;
import com.dream.service.recommender.base.impl.BaseRecommenderService;
import com.dream.service.recommender.domain.request.BaseRequest;
import com.dream.service.recommender.domain.request.FrontParam;
import com.dream.service.recommender.domain.response.RecommenderData;
import com.dream.service.recommender.domain.response.RecommenderItem;
import com.dream.service.recommender.domain.response.RecommenderSku;
import com.dream.service.wrapper.domain.entity.SPUData;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 根据分类召回
 * Created by duxy on 2016/04/25.
 */
public class DesignerDetailRecommender extends BaseRecommenderService{

    public static SearchRecallService searchRecallService;

    private Logger logger = Logger.getLogger(DesignerDetailRecommender.class);


    public SearchRecallService getSearchRecallService() {
        return searchRecallService;
    }
    @Autowired
    public void setSearchRecallService(SearchRecallService searchRecallService) {
        this.searchRecallService = searchRecallService;
    }

    public static DesignerAppService designerAppService;
    public DesignerAppService getDesignerAppService() {return designerAppService;    }
    @Autowired
    public void setDesignerAppService(DesignerAppService designerAppService) {
        this.designerAppService = designerAppService;
    }

    // 获取商品数据倍数
    private int multiple = 5;

    // 失效时间间隔 (sec)
    private int residue_time_interval =Integer.parseInt(ConfigUtil.getPro("residue_time_interval_dd"));

    // 缓存
    private final String cacheKey = "rec_designer_detail_";

    // 缓存
    private RedisCache redisCache = RedisCache.getInstance();

    @Override
    public BaseResponse<RecommenderData> getRecommender(BaseRequest<FrontParam> frontParamBaseRequest) {
        long sTime = System.currentTimeMillis();
        BaseResponse<RecommenderData> recommenderResponse = new BaseResponse<RecommenderData>();
        try {
            if (frontParamBaseRequest == null || frontParamBaseRequest.getParam() == null || frontParamBaseRequest.getParam().getUser() == null) {
                return buildResult(recommenderResponse, false, ErrorCode.PARAM_ERROR.getCode(), ErrorCode.PARAM_ERROR.getError_msg(), null);
            }
            FrontParam frontParam = frontParamBaseRequest.getParam();
            Integer cityId = frontParam.getCityId();
            int cid=-1;
//            int cid = ParamUtil.getCid(frontParam);
//            logger.debug(cid);
            Map<String,String > extraValues= ParamUtil.getExtraValues(frontParam);

            Integer designerId =Integer.parseInt(extraValues.get("designerId"));//设计师id

            Set designerIdSet=new HashSet<Integer>();
            designerIdSet.add(designerId);
            BaseListResponse baseListResponse=designerAppService.getDesignerTemplateProductSet(designerIdSet);
            System.out.println("desin----------"+JSONObject.toJSONString(baseListResponse));



            int pagesize = ParamUtil.getPageSize(frontParam);
            int page = ParamUtil.getPage(frontParam);
//            Map<Integer, Double> categoryWeightMap = new HashMap<Integer, Double>();
//            if (cid > 0) {
//                categoryWeightMap.put(cid, 1d);
//            }
            /*int skip = pagesize * (page - 1);*/
            //已经展示sku集合
            String pin = ParamUtil.getPin(frontParam);
            String uuid = ParamUtil.getUUid(frontParam);
            Set<Long> existSpus = gatherExistSpuInfo(pin, uuid, cid, page, pagesize);

            Set<Long> designerEditSpus= (Set<Long>) baseListResponse.getResult().getList();//设计师编辑的所有商品
            logger.debug("recommenderResponse==designerEditSpus"+JSONObject.toJSONString(designerEditSpus));
            logger.debug("recommenderResponse==existSpus"+JSONObject.toJSONString(existSpus));

            if(existSpus.equals(Collections.emptySet()))
                existSpus=designerEditSpus;
            else existSpus.addAll(designerEditSpus);

            List<ProductRecallResult> recallResults = gatherSearchRecallData(/*categoryWeightMap*/null, null, pagesize * multiple,designerId, existSpus, 0);
            RecommenderData recommenderData = buildResult(recallResults, designerEditSpus,cityId);
            recommenderResponse = buildResult(recommenderResponse, true, ErrorCode.OK.getCode(), "", recommenderData, 0, pagesize);
            Set<Long> spus = rebuildPositionInfo(recommenderResponse.getResult());
            backupExistSpuInfo(pin, uuid, spus, cid);
            long usedTime = System.currentTimeMillis() - sTime;
            recommenderData.setLatency(usedTime);
            recommenderResponse.setLatency(usedTime);
            logger.debug("usedTime:"+usedTime);
            logger.debug("recommenderResponse"+JSONObject.toJSONString(recallResults));

            logger.debug("recommenderResponse"+JSONObject.toJSONString(recommenderResponse));

            return recommenderResponse;
        } catch (Exception e) {

            logger.error("getRecommender:::",e);
            return buildResult(recommenderResponse, false, ErrorCode.PROCESS_ERROR.getCode(), e.getMessage(), null);
        }
    }

    public Set<Long> gatherExistSpuInfo(String pin, String uuid, int category, int pageNum, int pageSize) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) {
            return Collections.emptySet();
        }
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = cacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));
        if (pageNum == 1) {
            redisCache.delKey(key.getBytes());
            return Collections.emptySet();
        }
        Set<Long> spus = CacheUtil.getExistSpus(redisCache, key, (pageNum - 1) * pageSize);
        if (spus == null) {
            return Collections.emptySet();
        }
        return spus;
    }


    protected List<ProductRecallResult> gatherSearchRecallData(Map<Integer, Double> categoryWeightMap, Map<Integer, Double> labelWeightMap, int limit, Integer designerId,Set<Long> existSpus, int skip) {
        ProductSearchRequest request = new ProductSearchRequest();

        if (categoryWeightMap != null && !categoryWeightMap.isEmpty()) {
            request.setFrontCategoryWeightMap(categoryWeightMap);
        }
        if (labelWeightMap != null && !labelWeightMap.isEmpty()) {
            request.setLabelWeightMap(labelWeightMap);
        }
        request.setLimit(limit);
        request.setSkip(skip);

        request.setDesignerId(designerId);
        if (existSpus != null && !existSpus.isEmpty()) {
            request.setExistKeys(existSpus);
        }

        try {
            if (searchRecallService == null) {
                return null;
            }
            BaseResponse<List<ProductRecallResult>> recallResponse = searchRecallService.productSearchRecall(request);
            System.out.println("=============="+JSONObject.toJSONString(recallResponse));
            if (recallResponse.isSuccess()) {
                return recallResponse.getResult();
            }
        } catch (Exception e) {
            logger.error("gatherSearchRecallData:::",e);
        }
        return null;
    }

    /**
     * 更新位置信息
     * @param recommenderData
     * @return
     */
    public Set<Long> rebuildPositionInfo(RecommenderData recommenderData) {
        if (recommenderData == null || StringUtils.isEmpty(recommenderData.getList())) {
            return null;
        }
        List<RecommenderItem> items = recommenderData.getList();
        Set<Long> spus = new HashSet<Long>();
        int pos = 1;
        for (RecommenderItem recommenderItem : items) {
            recommenderItem.setPos(pos++);
            if (recommenderItem instanceof RecommenderSku) {
                try {
                    spus.add(((RecommenderSku) recommenderItem).getSpu());
                } catch (Exception e) {
                    logger.error("rebuildPositionInfo:::",e);
                }
            }
        }
        return spus;
    }

    public void backupExistSpuInfo(String pin, String uuid, Set<Long> spus, int category) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) return;
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = cacheKey.concat("_").concat(major_uid).concat("_").concat(String.valueOf(category));

        List<Long> cache = CacheUtil.backupCache(redisCache, key, spus, residue_time_interval, -1);
//        System.out.println("Backup Exist Spu :" + (cache == null ? "" : Arrays.toString(cache.toArray())));
    }

    /**
     * 封装结果
     *
     * @param recallResults
     * @param
     * @return
     */
    private RecommenderData buildResult(List<ProductRecallResult> recallResults, Set<Long>designerEditSpus,Integer cityId) {
        if (StringUtils.isEmpty(recallResults)) {
            return new RecommenderData();
        }
        RecommenderData<RecommenderSku> recommenderData = new RecommenderData<RecommenderSku>();
        List<RecommenderSku> recommenderSkus = new ArrayList<RecommenderSku>();
        recommenderData.setList(recommenderSkus);
        Set<Long> spus = new HashSet<Long>();
        for (ProductRecallResult recallResult : recallResults) {
            spus.add(recallResult.getSpu());
        }
        Map<Long, SPUData> spuDataMap = getBaseInfo(spus,cityId);
        logger.debug("spuDataMap::::"+JSONObject.toJSONString(spuDataMap));
        if (spuDataMap == null || spuDataMap.isEmpty()) {
            return recommenderData;
        }
        for (ProductRecallResult recallResult : recallResults) {
//            System.out.println(JSONObject.toJSONString(recallResult));
            logger.debug(JSONObject.toJSONString(recallResult));
            RecommenderSku recommenderSku = buildProduct(recallResult, spuDataMap.get(recallResult.getSpu()));
            if (recommenderSku != null) {
                recommenderSkus.add(recommenderSku);
            }
        }

//        BaseListResponse baseListResponse = feedService.listActiveFeedTopic();
//        Set<Long> ids = (Set<Long>) baseListResponse.getResult().getList();
//        System.out.println(ids);
//        BaseListResponse spuList = topicXmlService.getSpuByTopics(ids);

//a        System.out.println(spuList.getResult());
//        Set<Long> topicSpus= (Set<Long>) topicXmlService.getSpuByTopics((Set<Long>) baseListResponse.getResult().getList()).getResult().getList();
//        System.out.println(topicSpus);
//        System.out.println(designerEditSpus.size());
//        System.out.println(JSONObject.toJSONString(recommenderData.getList()));


//        List<RecommenderSku> recommenderSkuList = recommenderData.getList();

//        Set<Long> result = new HashSet<Long>();
//        result.addAll(designerEditSpus);

//        result.retainAll(recommenderDataSet);
//        System.out.println("zzzzzzz2:"+JSONObject.toJSONString(recommenderDataSet));
//        System.out.println("zzzzzzz3:"+JSONObject.toJSONString(result));
//        SortAndRankByDeSpu(recommenderData, designerEditSpus, spuDataMap);

//        Iterator<RecommenderSku> iter = recommenderSkuList.iterator();
//        System.out.println("======");
//        while(iter.hasNext()){
//            Long spu = iter.next().getSpu();
//            System.out.println(spu);
//            if(designerEditSpus.contains(spu)){
//                System.out.println("删除:"+spu);
//                iter.remove();
//            }
//        }

//        for(int i=0;i<recommenderSkuList.size();i++) {
//            if(designerEditSpus.contains(recommenderSkuList.get(i).getSpu())) {
//
//                System.out.println("zxc" + recommenderSkuList.get(i).getSpu());
//                recommenderData.getList().remove(recommenderSkuList.get(i));
//                i--;
//            }
//        }
        return recommenderData;
    }

    /**
     * 封装商品信息
     *
     * @param recallResult
     * @param spuData
     * @return
     */
    protected RecommenderSku buildProduct(ProductRecallResult recallResult, SPUData spuData) {
        if (recallResult == null || spuData == null || spuData.getSpuBase() == null || spuData.getStockStatus() == StockStatus.NO || spuData.getSpuBase().getIsPutOn() == 0) {
            return null;
        }
        RecommenderSku recommenderSku = new RecommenderSku();
        SpuBase spuBase = spuData.getSpuBase();
        recommenderSku.setSpu(spuBase.getSpu());
        recommenderSku.setSale_type(spuBase.getSale_type());
        recommenderSku.setMain_sku(spuBase.getMain_sku());
        recommenderSku.setMain_title(spuBase.getMain_title());
        recommenderSku.setW(recallResult.getQuality_score());
        recommenderSku.setCid3(recallResult.getCid3());
        if (recallResult !=null && recallResult.getOther_image_paths() != null) {
            recommenderSku.setImage_paths(recallResult.getOther_image_paths());
        }
        if(recallResult.getFront_cids()!=null && recallResult.getFront_cids().size() > 0)
            recommenderSku.setFront_category_id(recallResult.getFront_cids().get(0));//只取得一个，不知道会不会有问题

        if (!StringUtils.isEmpty(spuBase.getMain_image_url())) {
            recommenderSku.setMain_image_url(spuBase.getMain_image_url());
        } else { return null;}
        if (spuData.getSkuPrice() != null) {
            recommenderSku.setSkuPrice(spuData.getSkuPrice());
        } else { return null;}
        return recommenderSku;
    }


//    public RecommenderData SortAndRankByDeSpu(RecommenderData recommenderData, Set<Long> deSpus, Map<Long, SPUData> spuDataMap) {
//        if (recommenderData == null) {
//            return recommenderData;
//        }
//        List<RecommenderSku> recommenderSkus = recommenderData.getList();
//        /*System.out.println(recommenderSkus.size());
//        System.out.println(JSONObject.toJSONString(recommenderSkus));*/
//        if (StringUtils.isEmpty(recommenderSkus)) {
//            return recommenderData;
//        }
//        Map<Integer, List<RecommenderSku>> categoryItems = new HashMap<Integer, List<RecommenderSku>>();
//        for (RecommenderSku recommenderSku : recommenderSkus) {//根据cid重组所有spu
//            long spu = recommenderSku.getSpu();
////            System.out.println(spu);
//            SPUData spuData = spuDataMap.get(spu);
//            if (spuData == null) {
//                continue;
//            }
//            SpuBase spuBase = spuData.getSpuBase();
////            List<RecommenderSku> relSkus = categoryItems.get(spuBase.getCategory_id());
////            System.out.println(recommenderSku.getFront_category_id());
//            List<RecommenderSku> relSkus = categoryItems.get(recommenderSku.getFront_category_id());
//            if (relSkus == null) {
//                relSkus = new ArrayList<RecommenderSku>();
//                categoryItems.put(recommenderSku.getCid3(), relSkus);
////                System.out.println(recommenderSku.getCid3());
//            }
//            relSkus.add(recommenderSku);
//        }
//        List<RecommenderSku> sortRecommenderItems = new ArrayList<RecommenderSku>();
//        boolean loop = true;
//        do {
////            System.out.println("loop: 0");
//            List<RecommenderSku> subRecommenderItems = new ArrayList<RecommenderSku>(categoryItems.size());
////            System.out.println("cid size:"+categoryItems.size());
//            Iterator<Map.Entry<Integer, List<RecommenderSku>>> entryiterator = categoryItems.entrySet().iterator();
//            while (entryiterator.hasNext()) {
////                System.out.println("while: 0");
//                Map.Entry<Integer, List<RecommenderSku>> productentry = entryiterator.next();
//                List<RecommenderSku> productList = productentry.getValue();
//                if (StringUtils.isEmpty(productList)) {
//                    entryiterator.remove();
//                    continue;
//                }
//                RecommenderSku recommenderSku = productList.remove(0);
//                recommenderSku.setW(Math.random() * 100);
//
//                if (!deSpus.contains(recommenderSku.getSpu()))//给daily页面的topic中包含的商品增加0.4的权重
//                {
////                    System.out.println("asd");
//                    subRecommenderItems.add(recommenderSku);
//                }
//            }
//
//            sortRecommenderItems.addAll(subRecommenderItems);
//            if (categoryItems.isEmpty()) {
//                loop = false;
//            }
//            if (categoryItems.size() == 1) {
//                Set<Integer> keys = categoryItems.keySet();
//                Iterator<Integer> keyiterator = keys.iterator();
//                while (keyiterator.hasNext()) {
//                    Integer catid = keyiterator.next();
//                    sortRecommenderItems.addAll(categoryItems.get(catid));
//                }
//                loop = false;
//            }
//
//        } while (loop);
//        Collections.sort(sortRecommenderItems, new WeightComparator());
//        recommenderData.setList(sortRecommenderItems);
//        return recommenderData;
//    }
}
